package com.jinlejia.erp.jpush

import android.annotation.SuppressLint
import android.app.KeyguardManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.PowerManager
import android.os.SystemClock
import android.text.TextUtils
import cn.jpush.android.api.CustomMessage
import cn.jpush.android.service.JPushMessageReceiver
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.jinlejia.bbs.ui.BBSMainActivity
import com.jinlejia.erp.R
import com.jinlejia.erp.base.IApplication
import com.jinlejia.erp.common.NotifyUtil
import com.jinlejia.erp.ui.common.MainActivity
import com.jinlejia.erp.ui.customer.PushPopTelInfoActivity
import com.jinlejia.erp.ui.house.HouseCoreInfoActivity
import com.lab.Lab


/**
 * 自定义JPush message 接收器
 */
class JPushReceiver : JPushMessageReceiver() {
    override fun onRegister(context: Context?, s: String?) {
        super.onRegister(context, s)
        IApplication.setRegistrationID(s)
    }

    @SuppressLint("InvalidWakeLockTag")
    override fun onMessage(context: Context?, customMessage: CustomMessage) {
        super.onMessage(context, customMessage)
        val extra = customMessage.extra
        val message = customMessage.message
        println("极光推送：message:${message}"+"\n"+extra)
        var json: JSONObject? = null
        try {
            json = JSON.parse(message) as JSONObject
        } catch (ignored: Exception) {
        }
        if (json == null) {
            return
        }
        var extraJson:JSONObject? = null
        if (extra!=null){
            try {
                extraJson = JSON.parseObject(extra)
            } catch (ignored: Exception) {
            }
        }
        var code: String? = null
        if (json.containsKey("code")) {
            code = json.getString("code")
        }

        var link: String? = null
        if (json.containsKey("link")) {
            link = json.getString("link")
        }

        var content: String? = null
        if (json.containsKey("content")) {
            content = json.getString("content")
        }
        var title: String? = null
        if (json.containsKey("title")) {
            title = json.getString("title")
        }

        var isLearning:Int? = null
        if (extraJson!=null && extraJson.containsKey("isLearning")){
            isLearning = extraJson.getIntValue("isLearning")
        }
        println("极光推送：${code},${link},${content},${title},${isLearning}")
        when {
            //1 判断用户是否退出
            TextUtils.equals("removeDeviceCode", code) -> eventLogoff(context!!)
            //2 网页查看核心，推送核心信息到手机
            TextUtils.equals("pushInhome", link) -> eventPushInhome(context!!, code)
            //3 推送弹出客户联系信息
            TextUtils.equals("cusPushInhome", link) -> eventCusPushInhome(context!!, code)
            //4 消息推送
            else -> eventPush(context!!,code,link,content,title,isLearning)
        }
        val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
        powerManager.newWakeLock(
            PowerManager.ACQUIRE_CAUSES_WAKEUP or PowerManager.SCREEN_BRIGHT_WAKE_LOCK,
            "Notification"
        ).acquire(1000)

    }

    //region Event
    //1. 用户退出
    private fun eventLogoff(context: Context) {
        Lab.userLifecycle().onLogout(context)
    }

    //2. 查看核心
    private fun eventPushInhome(context: Context, code: String?) {
        val mIntent = Intent(context, HouseCoreInfoActivity::class.java)
        mIntent.putExtra("content", code)
        mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        context.startActivity(mIntent)
        val manager = context.getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
        val locked = manager.isKeyguardLocked
        if (locked) {
            val mmIntent = Intent(context, HouseCoreInfoActivity::class.java)
            mmIntent.putExtra("content", code)
            val pIntent = PendingIntent.getActivity(
                context,
                SystemClock.uptimeMillis().toInt(),
                mmIntent,
                PendingIntent.FLAG_UPDATE_CURRENT
            )
            val smallIcon = R.mipmap.jpush_notification_icon
            val ticker = "点击查看房源电话"
            val title = "房源电话推送"
            val content = "点击查看房源电话"
            val notify1 = NotifyUtil(context, 2)
            notify1.notify_normail_moreline(
                pIntent,
                smallIcon,
                ticker,
                title,
                content,
                true,
                true,
                true
            )
        }
    }

    //3.推送弹出客户联系信息
    private fun eventCusPushInhome(context: Context, code: String?) {
        val mIntent = Intent(context, PushPopTelInfoActivity::class.java)
        mIntent.putExtra("content", code)
        mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        context.startActivity(mIntent)

        val manager = context.getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
        val locked = manager.isKeyguardLocked
        if (!locked) { //当未锁屏时
            val pIntent = PendingIntent.getActivity(
                context,
                SystemClock.uptimeMillis().toInt(),
                mIntent,
                PendingIntent.FLAG_UPDATE_CURRENT
            )
            val smallIcon = R.mipmap.jpush_notification_icon
            val ticker = "点击查看房源电话"
            val title = "房源电话推送"
            val content = "点击查看房源电话"
            val notify1 = NotifyUtil(context, 2)
            notify1.notify_normail_moreline(
                pIntent,
                smallIcon,
                ticker,
                title,
                content,
                true,
                true,
                true
            )
        }

    }


    //4. 推送和消息跳转
    private fun eventPush(
        context: Context,
        code: String?,
        link: String?,
        content: String?,
        title: String?,
        isLearning: Int?
    ) {
        val mIntent = Intent()
        mIntent.putExtra("code",code)
        mIntent.putExtra("url",link)
        mIntent.putExtra("content",content)
        mIntent.putExtra("title",title)
        if (isLearning==1){ //跳转至社区
            mIntent.setClass(context,BBSMainActivity::class.java)
        }else{ //跳转至首页
            mIntent.setClass(context,MainActivity::class.java)
        }

        val smallIcon = R.mipmap.jpush_notification_icon
        val ticker = "您有一条新通知"
        val notifyTitle by lazy {
            if (TextUtils.equals(link,"noticedetails")){
                "进了家公告"
            }else{
                "InHome"
            }
        }

        val notify1 = NotifyUtil(context, 2)
        val pIntent = PendingIntent.getActivity(
            context,
            SystemClock.uptimeMillis().toInt(), mIntent, PendingIntent.FLAG_UPDATE_CURRENT
        )
        notify1.notify_normail_moreline(
            pIntent,
            smallIcon,
            ticker,
            notifyTitle,
            content,
            true,
            true,
            false
        )
    }
    //endregion


}
